package com.qinsoft.frame.listener;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.qinsoft.frame.common.AppUtil;
import com.qinsoft.frame.common.UserInfo;
import com.qinsoft.frame.common.UserUtil;
import com.qinsoft.frame.messages.WriteMessage;
import com.qinsoft.frame.utils.CodeUtil;
import com.qinsoft.frame.utils.JsonConvert;
import com.qinsoft.frame.utils.QinConfig;
import com.taobao.api.internal.util.WebUtils;

public class TaobaoFilter implements Filter{
	QinConfig config = QinConfig.getInstance("taobao");
	String appKey = config.getValue("appkey");
	String secret = config.getValue("secret");
	String redirect = QinConfig.getInstance("taobao").getValue("redirect");

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) servletResponse;		//HttpServletResponse对象
		HttpServletRequest request = (HttpServletRequest) servletRequest;			//HttpServletRequest对象
		HttpSession session = request.getSession();									//HttpSession对象
		//request.getCookies();
		String code = request.getParameter("code");		//code
		String state = request.getParameter("state");	//state
		String type = request.getParameter("type");		//type
		long timestamp = new Date().getTime();			//时间戳
		UserInfo userInfo;
		/*如果已经登录*/
		if(code!=null||session.getAttribute("code")!=null){
			/*如果是淘宝登录*//*如果是新浪登录*/
			if(state!=null||type!=null){
			    //如果是淘宝登录
			    if(state!=null){type="taobao";}
				//如果是第一次登录
				userInfo = Oauth(code,type);
				//如果抛出异常
				if(userInfo==null){response.sendRedirect(redirect);return;}
				//设置权限
				userInfo = AppUtil.select(userInfo);
				//保存用户信息
				UserUtil.getInstance().addUserInfo(session.getId(), userInfo);
				//如果是短授权登录
				if(state!=null&&state.equals("short")){
					request.setCharacterEncoding("utf-8"); 
					response.setCharacterEncoding("utf-8");
					response.setContentType("text/html; charset=utf-8");
					PrintWriter w= response.getWriter(); 
					w.print("<script> parent.document.getElementById('smarttaobao').closeWindow(); </script>");
					w.flush();
					w.close();
					return;
				}
				session.setAttribute("code", code);
				response.addCookie(new Cookie("session", userInfo.getSessionKey()));
			}
			
			//jsSDK签名
			String mysign = "";
			try {
				mysign = CodeUtil.sign(secret+"app_key"+appKey+"timestamp"+timestamp+secret, secret);
			} catch (Exception e) {
				WriteMessage.WriteErrorLog(this.getClass().toString()+".doFilter()", e);
			}
			//设置Cookie
			response.addCookie(new Cookie("appkey", appKey));
			response.addCookie(new Cookie("sign", mysign));
			response.addCookie(new Cookie("timestamp", timestamp+""));
			if(type!=null){
				response.sendRedirect("index.html?rand="+new Date().getTime());
				return;
			}
			else{
				chain.doFilter(request, response);
			}
		}
		/*如果没有登录*/
		else{
			response.sendRedirect(redirect);
		}
	}
	/**
	 * 获得短授权
	 * @param code：授权码
	 * @throws IOException 
	 */
	public UserInfo Oauth(String code,String type) throws IOException{
		QinConfig config = QinConfig.getInstance(type);
		Map<String, String> param = new HashMap<String, String>();
		param.put("grant_type", "authorization_code");
		param.put("code", code);
		param.put("client_id", config.getValue("appkey"));
		param.put("client_secret", config.getValue("secret"));
		param.put("redirect_uri", config.getValue("callback"));
		param.put("scope", "promotion");
		String message = "";
		try {
			message = WebUtils.doPost(config.getValue("token"), param, 3000, 3000);
			return JsonConvert.toUserInfo(message);
		} catch (IOException e) {
			WriteMessage.WriteErrorLog(this.getClass().toString()+"Oauth()", e);
		}
		return null;
	}

	@Override
	public void destroy() {
		
	}
	
	@Override
	public void init(FilterConfig filterConfig){
		
	}
}
